import React, { useEffect, useMemo, useRef, useState } from "react";
import { DeskTopS, FullBtn } from "./styled";

import Folder from "./folder";
import DeskMenu from "./mouseMenu/deskMenu";
import FolderMenu from "./mouseMenu/folderMenu";
import BarMenu from "./mouseMenu/barMenu";
import SelectBox from "./selectBox";
import BackGround from "../backGround";
import Explorer from "@/components/folderExplorer";
import IFrame from "../iframe";
import Terminal from "../terminal";

import { iframeData } from "@/common/deskIframe.json";
import { UID } from "@/contains/seesionKeys";
import dataManager from "@/utils/dataManager";
import VsCode from "../vsCode";
import Calculator from "../calculator";
import Notebook from "../notebook";
import TextEditor from "../textEditor";
import Calendar from "../calendar"
import PdfEditor from "../pdfEditor";
import QQMusic from "../qqMusic";

const DeskTopCompnent = ({ state, dispatch, fullScreenHandler }) => {
  const { folderData, isFullScreen, deskMenuVisible, folderMenuVisible, barMenuVisable, isRenameId,
    isFolderVisiable, deskRequestId, isShowBackGround, backGroundUrl, iframeList } = state; // 桌面数据和满屏状态
  const uid = localStorage.getItem(UID);
  const deskNode = useRef(null); // 获取桌面节点
  const [useDom, setUseDom] = useState([]); // 使用的文件夹元素
  const [hoverId, setHoverId] = useState(-1); // 悬浮的id
  const [isShiftKey, setIsShiftKey] = useState(false); // 使用是否是左键

  // 获取页面文件夹数据方法
  const getData = async () => {
    try {
      // 确保数据库已初始化
      await dataManager.initialize();

      const folders = await dataManager.getDesktopFolders();
      console.log('获取到桌面文件夹:', folders);
      dispatch({
        type: "setState",
        payload: {
          folderData: [...iframeData, ...folders],
        },
      });
    } catch (error) {
      console.error('获取桌面数据失败:', error);
      // 出错时只显示内置应用
      dispatch({
        type: "setState",
        payload: {
          folderData: [...iframeData],
        },
      });
    }
  };

  // 初始化
  useEffect(() => {
    document.onkeydown = keyDownHandler;
    document.onkeyup = keyUpHandler;
    document.onselectstart = () => false
    return () => {
      // 销毁监听事件
      document.onkeydown = null;
      document.onkeyup = null;
    };
  }, []);

  useEffect(() => {
    getData();
  }, [deskRequestId]);

  // 组件挂载时获取数据
  useEffect(() => {
    getData();
  }, []);

  // 当用户登录状态改变时重新获取数据
  useEffect(() => {
    if (uid) {
      console.log('User logged in, loading desktop data...', uid);
      getData();
    }
  }, [uid]);

  const _handClickConetextMenu = (e) => {
    e.preventDefault();
    e.stopPropagation();
    dispatch({
      type: "setState",
      payload: {
        deskMenuVisible: true,
        folderMenuVisible: false,
        barMenuVisable: false,
        menuType: "desk",
        deskMenuX: e.clientX,
        deskMenuY: e.clientY,
        selectFid: 0
      },
    });
  };

  // 鼠标按压事件
  const keyDownHandler = (e) => {
    if (e.key === "Shift") {
      setIsShiftKey(true);
    }
  };

  // 鼠标弹起事件
  const keyUpHandler = (e) => {
    setIsShiftKey(false);
  };

  // 文件夹点击事件
  const folderHandler = (e, id) => {
    e.preventDefault();
    e.stopPropagation();
    dispatch({
      type: "setState",
      payload: {
        deskMenuVisible: false,
        folderMenuVisible: false,
        barMenuVisable: false,
      },
    });
    if (!isShiftKey) {
      setUseDom([id]);
    } else {
      if (!useDom.includes(id)) setUseDom(useDom.concat([id]));
      else {
        const data = useDom.slice();
        const index = useDom.indexOf(id);
        data.splice(index, 1);
        setUseDom(data);
      }
    }
  };
  /**
   * 记录鼠标在元素内部的位置
   * innerTop：表示鼠标距离元素上方的距离
   * innerLeft：表示鼠标距离元素左边的距离
   */
  let innerTop;
  let innerLeft;
  /**
   *
   * @param {拖拽开始事件} e
   */
  const onDragStart = (e) => {
    innerTop = e.clientY;
    innerLeft = e.clientX;
  };

  /**
   *
   * @param {鼠标拖拽的结束事件} e
   */
  const onDragEnd = (e) => {
    e.preventDefault();
    let left = e.clientX - innerLeft;
    let top = e.clientY - innerTop;
    console.log(folderData);
    const dataList = JSON.parse(JSON.stringify(folderData));
    upDateuseDomData(dataList, left, top, hoverId);
    dispatch({
      type: "setState",
      payload: {
        folderData: dataList,
      },
    });
  };

  const upDateuseDomData = (dataList, left, top, hoverId) => {
    // 批量更新位置
    if (useDom.includes(hoverId)) {
      useDom.forEach((id) => {
        const folder = dataList.find((item) => item.fid === id);
        updateDragStatus(folder, left, top);
      });
    } else {
      const folder = dataList.find((item) => item.fid === hoverId);
      updateDragStatus(folder, left, top);
      setUseDom([hoverId]);
    }
  };

  const updateDragStatus = (folder, left, top) => {
    if (folder.x + left < 0) {
      folder.x = 10;
    } else if (folder.x + left > document.documentElement.clientWidth - 60) {
      folder.x = document.documentElement.clientWidth - 60;
    } else {
      folder.x = folder.x + left;
    }
    if (folder.y + top < 0) {
      folder.y = 10;
    } else if (folder.y + top > document.documentElement.clientHeight - 70) {
      folder.y = document.documentElement.clientHeight - 70;
    } else {
      folder.y = folder.y + top;
    }
  };

  // 实现框选
  const [showSelectBox, setShowSelectBox] = useState(false); // 是否开启框选功能
  const [startX, setStartX] = useState(-1); //  鼠标按下起始位置横坐标
  const [startY, setStartY] = useState(-1); //  鼠标按下起始位置纵坐标
  const [leftMouseDown, setLeftMouseDown] = useState(false); // 鼠标左键是否按下

  // 监听桌面的点击事件，主要做清空状态操作
  function mouseDownListener(e) {
    if (e.target == e.currentTarget) {
      // 防止事件冒泡的小操作
      setUseDom([]);
      setLeftMouseDown(true);
      setStartX(e.clientX);
      setStartY(e.clientY);
    }
  }

  // 监听是否按下，按下之后就绑定鼠标移动事件
  useEffect(() => {
    if (leftMouseDown) {
      deskNode.current.onmousemove = mouseMoveListener;
      document.onmouseup = mouseUpListener;
    } else {
      document.onmouseup = null;
      setShowSelectBox(false);
      // 按压松开把NowX设置为startX，去除点击影响
      setNowX(startX);
      setNowY(startY);
    }
  }, [leftMouseDown]);

  //  鼠标移动监听器，更新鼠标移动距离
  let [nowX, setNowX] = useState(-1);
  let [nowY, setNowY] = useState(-1);

  function mouseMoveListener(e) {
    e.preventDefault();
    setNowX(e.clientX);
    setNowY(e.clientY);
  }
  // 计算选择长度
  const selectBoxWidth = useMemo(() => {
    return nowX - startX;
  }, [nowX, nowY]);
  // 计算选择宽度
  const selectBoxHeight = useMemo(() => {
    return nowY - startY;
  }, [nowY, startY]);

  useEffect(() => {
    if (Math.abs(selectBoxWidth) > 10 && Math.abs(selectBoxHeight) > 10) {
      setShowSelectBox(true);
      folderData.forEach((item) => {
        if (
          item.x > Math.min(nowX, startX) - 60 &&
          item.x < Math.max(nowX, startX) &&
          item.y > Math.min(nowY, startY) - 80 &&
          item.y < Math.max(nowY, startY)
        ) {
          if (!useDom.includes(item.fid)) setUseDom(useDom.concat(item.fid));
        } else {
          if (useDom.includes(item.fid)) {
            const index = useDom.indexOf(item.fid);
            useDom.splice(index, 1);
            setUseDom(useDom);
          }
        }
      });
    }
  }, [selectBoxHeight, selectBoxWidth]);

  //  鼠标左键抬起监听器
  function mouseUpListener(e) {
    deskNode.current.onmousemove = null;
    deskNode.current.onmousedown = null;
    setLeftMouseDown(false);
  }

  // 本行开始设置鼠标移入事件
  function mouseOverHandler(e, id) {
    setHoverId(id);
  }
  function mouseOutHandler() {
    setHoverId(-1);
  }
  function dragOver(e) {
    e.preventDefault();
  }
  return (
    <DeskTopS
      ref={deskNode}
      onMouseDown={(e) => mouseDownListener(e)}
      onContextMenu={_handClickConetextMenu}
      onDragOver={dragOver}
      url={backGroundUrl}
    >
      {folderData?.map((item, index) => (
        <Folder
          info={item}
          isFocus={useDom.includes(item.fid)}
          isHover={hoverId === item.fid}
          folderHandler={(e) => folderHandler(e, item.fid)}
          keyDownHandler={(e) => keyDownHandler(e)}
          onDragStart={(e) => onDragStart(e)}
          onDragEnd={(e) => onDragEnd(e)}
          isStatic={!!item.isStatic}
          isRename={isRenameId.includes(item.fid)}
          key={index}
          state={state}
          dispatch={dispatch}
          onMouseOver={(e) => {
            mouseOverHandler(e, item.fid);
          }}
          onMouseOut={mouseOutHandler}
        />
      ))}
      <FullBtn onClick={fullScreenHandler}>
        {!isFullScreen ? "全屏显示" : "取消全屏"}
      </FullBtn>
      {deskMenuVisible && (
        <DeskMenu state={state} dispatch={dispatch}></DeskMenu>
      )}
      {folderMenuVisible && (
        <FolderMenu
          state={state}
          dispatch={dispatch}
          hoverId={hoverId}
        ></FolderMenu>
      )}
      {showSelectBox && (
        <SelectBox
          info={{ startX, startY, selectBoxWidth, selectBoxHeight }}
        ></SelectBox>
      )}
      {/* <Terminal /> */}
      {/* <VsCode /> */}
      {/* <Calculator /> */}
      {/* <Notebook /> */}
      {/* <TextEditor /> */}
      {/* <Calendar /> */}
      {/* <PdfEditor /> */}
      {/* <QQMusic /> */}
      {barMenuVisable && <BarMenu state={state} dispatch={dispatch}></BarMenu>}
      {isFolderVisiable && <Explorer state={state} dispatch={dispatch} />}
      {isShowBackGround && <BackGround state={state} dispatch={dispatch} />}
      {iframeList.length !== 0 && <IFrame state={state} dispatch={dispatch} />}
    </DeskTopS>
  );
};

export default DeskTopCompnent;
